export default class LayerManager {
    constructor(viewer) {
        this.viewer = viewer;
        this._layersList = [];
        this.geojsonData = {};
        this.pointPrimitive = viewer.scene.primitives.add(new Cesium.PointPrimitiveCollection());
        this.polymericDataSource = null;//聚合对象
        this.billboards = viewer.scene.primitives.add(new Cesium.BillboardCollection({
            scene: viewer.scene
        }));
        this.labels = viewer.scene.primitives.add(new Cesium.LabelCollection({
            scene: viewer.scene
        }));
        this.labels1 = new Cesium.LabelCollection({
            scene: viewer.scene
        });
        this._imageryMap = new Array();
        this.currentGeoJson = null;
        this.init();
        this.Num = 0;
        this.Tile = null;
        this.vecTile = null;
    }
    init() {
        this.viewer.scene.globe.showGroundAtmosphere = false; //关闭地面大气圈
        this.viewer.scene.skyAtmosphere.show = false; //关闭天空大气圈
        window.css3Elements = []
        window.css3Renderer = new fmh.Css3Renderer(css3Elements,true)
        const leftClickHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
        leftClickHandler.setInputAction(function(movement){
            const pickedObject = viewer.scene.pick(movement.endPosition);
            if(Cesium.defined(pickedObject)){
                document.body.style.cursor = "pointer"
            }else{
                document.body.style.cursor = "default"
            }
        },Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        leftClickHandler.setInputAction(function (movement) {
            const pickedObject = viewer.scene.pick(movement.position)
            if(pickedObject){
                if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.primitive.leftClick === 'function') {
                    //pointPrimitive 选中状态
                    console.log("输出")
                    pickedObject.primitive.leftClick(pickedObject.id)
                } else if(Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.leftClick === 'function') {
                    //entity 选中状态
                    console.log("初始化选中")
                    pickedObject.id.leftClick(pickedObject.id)
                } else if(Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.leftClick === 'function') {
                    //entity 选中状态
                    console.log("初始化选中")
                    pickedObject.id.leftClick(pickedObject.id)
                }
            }else{
                if( document.getElementById('zaihaiInfo') ){
                    css3Renderer.remove('zaihaiInfo')
                }
                viewer.entities.removeById("tubiao")
                // ie中通过GraphicLayer加载的对象可以通过该方法拾取
                // const pickedObject = that.viewer.graphicLayer.pickByCoordinate(movement.position.x, movement.position.y)
                
            }

            
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }
    addLayer(type, treeNode) {
        switch (type) {
            case 'pngxyz':
                let layerpngxyz = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                    url: treeNode.url,
                    tilingScheme: new Cesium.GeographicTilingScheme()
                }));
                this._imageryMap.push({
                    type: layerId,
                    layer: layerpngxyz
                });
                break;
            case 'geojson':
                Cesium.Math.setRandomNumberSeed(0); //设置随机数种子
                let promise = Cesium.GeoJsonDataSource.load(treeNode.url); //geojson面数据
                promise.then(function (dataSource) {
                    this.viewer.dataSources.add(dataSource);
                    // var entities = dataSource.entities.values;
                    // var colorHash = {};
                    // for (var i = 0; i < entities.length; i++) {
                    //     var entity = entities[i];
                    //     entity.polygon.material = Cesium.Color.red;
                    //     entity.polygon.strokeWidth = 10;
                    //     entity.polygon.outline = false;
                    // }
                });
                break;
            case 'img':
                let layerimg = this.viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider({
                    url: treeNode.imgUrl,
                    rectangle: Cesium.Rectangle.fromDegrees(117.20, 31.33, 117.92, 31.82)
                }));
                this._imageryMap.push({
                    type: layerId,
                    layer: layerimg
                });
                break;
            case 'entity':
                let shareEntities = [];
                if (typeof (treeNode.flag) != 'undefined' && treeNode.flag == "ydyl") {
                    for (let i = 0; i < treeNode.billboards.length; i++) {
                        let label = new Cesium.LabelGraphics({
                            text: treeNode.billboards[i].text,
                            font: '20px Helvetica',
                            fillColor: Cesium.Color.BLANCHEDALMOND,
                            // outlineColor: Cesium.Color.block,
                            outlineColor: "#6E7018",
                            outlineWidth: 3,
                            pixelOffset: new Cesium.Cartesian2(0, -30),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE
                        });
                        let entity = this.viewer.entities.add({
                            id: layerId,
                            position: Cesium.Cartesian3.fromDegrees(treeNode.billboards[i].lon, treeNode.billboards[i].lat),
                            label: label,
                            billboard: {
                                image: treeNode.url
                            }
                        });
                        shareEntities.push(entity);
                    }
                } else {
                    for (let i = 0; i < treeNode.billboards.length; i++) {
                        let label = new Cesium.LabelGraphics({
                            text: treeNode.billboards[i].text,
                            font: '20px Helvetica',
                            fillColor: Cesium.Color.BLANCHEDALMOND,
                            // outlineColor: Cesium.Color.block,
                            outlineColor: "#6E7018",
                            outlineWidth: 3,
                            pixelOffset: new Cesium.Cartesian2(0, -30),
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE
                        });
                        let entity = this.viewer.entities.add({
                            id: "entity" + i,
                            position: Cesium.Cartesian3.fromDegrees(treeNode.billboards[i].lon, treeNode.billboards[i].lat),
                            label: label,
                            billboard: {
                                image: treeNode.url
                            }
                        });
                        shareEntities.push(entity);
                    }
                }
                this._imageryMap.push({
                    type: layerId,
                    layer: shareEntities
                });
                break;
        }
    }
    removeLayer(item, layerId) {
        for (let i = 0; i < this._imageryMap.length; i++) {
            if (this._imageryMap[i].type == layerId) {
                if (item.type == "arcgis" || item.type == 'tms' || item.type == 'wms' || item.type == 'xyz' || item.type == 'pngxyz' || item.type == 'evia' || item.type == 'wmts') {
                    this.viewer.imageryLayers.remove(this._imageryMap[i].layer, true);
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "whiteModel" || item.type == 'geojson') {
                    if (this._imageryMap[i].layer) {
                        this._imageryMap[i].layer.destroy();
                    }
                    this.viewer.dataSources.removeAll();
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "video") {
                    this.viewer.entities.removeAll();
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "fineModel" || item.type == 'qingxieModel' || item.type == '3dTiles' || item.type == 'guomaoyinquAnalysis') {
                    this.viewer.scene.primitives.remove(this._imageryMap[i].layer)
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == "landAnalysis") { }
                if (item.type == "diffAnalysis") { }
                if (item.type == "terrain") {
                    this.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({
                        ellipsoid: Cesium.Ellipsoid.WGS84
                    });
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == 'timeline') { }
                if (item.type == "juanlian") {

                    for (const layer of this._imageryMap[i].layer) {
                        this.viewer.imageryLayers.remove(layer, true);
                    }
                    this._imageryMap.splice(i, 1);
                    // item.handler.destroy();
                }
                if (item.type == 'poi') {
                    this.viewer.dataSources.remove(this._imageryMap[i].layer)
                    this._imageryMap.splice(i, 1);
                }
                if (item.type == 'entity') {
                    // for (const entity of this._imageryMap[i].layer) {
                    //     this.viewer.entities.remove(entity);
                    // }
                    this.viewer.entities.removeAll();
                    this._imageryMap.splice(i, 1);
                }
            }
        }
    }
    addGeojson(url,color='rgba(115,227,230,1)'){
        let that = this
        Cesium.GeoJsonDataSource.load(url, {
            //clampToGround: false, //开启贴地
            stroke: Cesium.Color.fromCssColorString(color),
            strokeWidth: 5,
            fill: Cesium.Color.fromCssColorString('rgba(115,227,230,1)').withAlpha(.3)
        }).then(dataSource => {
            this.viewer.dataSources.add(dataSource)
            that.geojsonData[url] = dataSource
            //that.viewer.flyTo(dataSource);
        })
    }
    addGeojsonZoom(url){
        let that = this
        Cesium.GeoJsonDataSource.load(url, {
            //clampToGround: false, //开启贴地
            stroke: Cesium.Color.fromCssColorString('rgba(115,227,230,1)'),
            strokeWidth: 10,
            fill: Cesium.Color.fromCssColorString('rgba(115,227,230,1)').withAlpha(0.3)
        }).then(dataSource => {
            this.viewer.dataSources.add(dataSource)
            that.geojsonData[url] = dataSource
            // that.viewer.flyTo(dataSource);
        })
    }
    removeGeojson(url) {
        if (url) {
            this.viewer.dataSources.remove(this.geojsonData[url])
            this.geojsonData[url] = null
        }
    }
    addBillboard(id,lon,lat,img){
        let entity = this.viewer.entities.add({
            id: id,
            position: Cesium.Cartesian3.fromDegrees(lon, lat),
            billboard: {
                image: img,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                //color : Cesium.Color.LIME, // default: WHITE
                width: 40,
                height: 40,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
    }
    addPrimitivesBillboards(data,img,dataType,type,event){
        data.forEach((item)=>{
            if(item.lng){
                let billboard =  this.billboards.add({
                    position: Cesium.Cartesian3.fromDegrees( parseFloat(item.lng), parseFloat(item.lat),100),
                    id: {
                        item:item,
                        dataType:dataType
                    },
                    image : img,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
                    horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    scaleByDistance: new Cesium.NearFarScalar(100000, 1, 1000000, .5),
                    width : "28",
                    height : "42"
                })
                if (type && event) {
                    billboard[type] = event
                }
            }else{
                let billboard =  this.billboards.add({
                    position: Cesium.Cartesian3.fromDegrees( parseFloat(item.lon), parseFloat(item.lat),100),
                    id: {
                        item:item,
                        dataType:dataType
                    },
                    image : img,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
                    horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    scaleByDistance: new Cesium.NearFarScalar(100000, 1, 1000000, .5),
                    width : "28",
                    height : "42"
                })
                if (type && event) {
                    billboard[type] = event
                }
            }
        }) 
    }
    addBillboards(item,img,datatype,kbId,zidatatype,type){
        // console.log(item)
        if(item.sfkx == null || item.sfkx == "是"){
            window.billboard = this.billboards.add({
                position: Cesium.Cartesian3.fromDegrees( parseFloat(item.lng), parseFloat(item.lat),100),
                id:{
                    id:item.id,
                    kbId:kbId,
                    dataType:datatype,
                    zidatatype:zidatatype,
                    type:type,
                },
                image: img,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
                horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scaleByDistance: new Cesium.NearFarScalar(100000, 1, 1000000, .5),
                width : "30",
                height : "35"
            })
        }
    }
    // addBillboardicon(item,img,datatype,kbId,zidatatype){
    //     let billboard = this.billboards.add({
    //         position: Cesium.Cartesian3.fromDegrees( parseFloat(item.lng), parseFloat(item.lat),100),
    //         id:{
    //             id:item.id,
    //             kbId:kbId,
    //             dataType:datatype,
    //             zidatatype:zidatatype
    //         },
    //         image: img,
    //         disableDepthTestDistance: Number.POSITIVE_INFINITY,
    //         heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
    //         horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
    //         verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    //         scaleByDistance: new Cesium.NearFarScalar(100000, 1, 1000000, .5),
    //         width : "30",
    //         height : "35"
    //     })
    // }
    removeBillboard(id){
        this.viewer.entities.removeById(id)
    }
    addPloygonLine(id, arr,data) {
        this.viewer.entities.add({
            id: id,
            dataSource:data,
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
                material: Cesium.Color.fromCssColorString("rgba(115,227,230,1)").withAlpha(.3),
                extrudedHeight : 10,
                clampToGround: false,
                //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            },
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArray(arr),
                clampToGround: false,
                width: 2,
                material: new Cesium.PolylineOutlineMaterialProperty({
                    color: Cesium.Color.fromCssColorString("rgba(115,227,230,1)").withAlpha(1),
                    outlineWidth: 1,
                    outlineColor: Cesium.Color.fromCssColorString("rgba(115,227,230,1)").withAlpha(1),
                }),
            },
        });
        viewer.flyTo(arr[0])
    }
    getCenter(){
        let centerx = (this.viewer.camera.positionCartographic.longitude * 180) / Math.PI
        let centery = (this.viewer.camera.positionCartographic.latitude * 180) / Math.PI
        let height = Math.ceil(this.viewer.camera.positionCartographic.height)
        let heading = this.viewer.camera.heading
        let pitch = this.viewer.camera.pitch
        let roll = this.viewer.camera.roll
        return centerx + ',' + centery + ',' + height + ',' + heading + ',' + pitch + ',' + roll
    }
    fly( lon , lat , alt , heading , pitch , roll ) {
        this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(lon , lat , alt), // 设置位置
            orientation: {
                heading: heading, // 方向
                pitch: pitch, // 倾斜角度
                roll: roll
            },
        });
    }
    addDefaultLayer(val) {
        if (val.isactive) {
            switch (val.name) {
                case '全球影像':
                    let layerwms = this.viewer.imageryLayers.addImageryProvider(new GV.WebMapServiceImageryProvider({
                        url: "http://192.168.4.183:8310/geoserverplus/gwc/service/wms",
                        layers: "北京-PNG-4326",
                        parameters: {
                            format: 'image/png'
                        },
                        srs: 'EPSG:4326'
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layerwms
                    })
                    break;
                case '全球地形':
                    break;
                case '全球海图':
                    let layerxyz = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                        url: "/layer/data/seamap/{z}/{x}/{y}.png"
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layerxyz
                    })
                    break;
                case '全球矢量':
                    let layer = this.viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
                        url: "/layerdata/osm/{z}/{y}/{x}.png"
                    }));
                    this._layersList.push({
                        name: val.name,
                        layer: layer
                    })
                    break;
            }
        } else {
            this.removeDefaultLayer(val)
        }
        for (let item of this._layersList) {
            if (val.name !== item.name) {
                this.removeDefaultLayer(item)
            }
        }
    }
    removeDefaultLayer(item) {
        for (let i = 0; i < this._layersList.length; i++) {
            if (this._layersList[i].name == item.name) {
                this.viewer.imageryLayers.remove(this._layersList[i].layer, true);
                this._layersList.splice(i, 1);
            }
        }
    }
    removeAllLayer() {
        for (let i = 0; i < this._layersList.length; i++) {
            this.viewer.imageryLayers.remove(this._layersList[i].layer, true);
        }
        this._layersList = [];
    }
    removeAll(){
        //清除geojson
        this.viewer.dataSources.removeAll()
        //清除弹出框
        if(document.getElementById('zaihaiInfo')){
            css3Renderer.remove('zaihaiInfo')
        }
        //清除弹出框
        if( document.getElementById('descDialog') ){
            css3Renderer.remove('descDialog')
        }
        //清除pointPrimitive
        this.pointPrimitive.removeAll()
        //清除entities
        this.billboards.removeAll()
        this.viewer.entities.removeAll()
        //清除3dTiles
        this.remove3dTiles()
        //清除聚合
        this.polymerizationRemove();
        const oneDiv1 = window.document.getElementById("infobox1");
        if(oneDiv1){
            oneDiv1.style.display = "none";
        }
        // oneDiv2.style.display = "none";
        // oneDiv3.style.display = "none";
        //复位
        //this.fly(109.83211083772301,19.267705800908967,498832,0.08093540923089115,-1.5652486674208381,0)
    }
    cleanLayer() {
        for (let i = 0; i < this._imageryMap.length; i++) {
            if (this._imageryMap[i].layer instanceof Array) {
                // for (const entity of this._imageryMap[i].layer) {
                //     this.viewer.entities.remove(entity);
                // }
                this.viewer.entities.removeAll();
            } else {
                this.viewer.imageryLayers.remove(this._imageryMap[i].layer, true);
            }
        }
        this._imageryMap = [];
    }
    addPrimitives(){
        var billboards = scene.primitives.add(new Cesium.BillboardCollection());
        billboards.add({
            position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
            image : 'url/to/image'
        });
    }
    addPoint = function(data,colorString,dataType,type,event) {
        //comjs.pointPrimitive.removeAll();
        let that = this;
        data.forEach((item)=>{
            if(item.lng){
                if(that.pointPrimitive){
                    let point = that.pointPrimitive.add({
                        position: Cesium.Cartesian3.fromDegrees( parseFloat(item.lng), parseFloat(item.lat),100),
                        color: Cesium.Color.fromCssColorString(colorString),
                        id: {
                            item:item,
                            dataType:dataType
                        },
                        clampToGround: false,
                    })
                    if (type && event) {
                        point[type] = event
                    }
                }
            }
        }) 
    }
    addPointLonLat = function(data,colorString,dataType,type,event) {
        //comjs.pointPrimitive.removeAll();
        let that = this;
        data.forEach((item)=>{
            if(item.lon){
                if(that.pointPrimitive){
                    let point = that.pointPrimitive.add({
                        position: Cesium.Cartesian3.fromDegrees(parseFloat(item.lon), parseFloat(item.lat),10),
                        color: Cesium.Color.fromCssColorString(colorString),
                        id: {
                            item:item,
                            dataType:dataType
                        },
                        clampToGround: true,
                    })
                    if (type && event) {
                        point[type] = event
                    }
                }
            }
        }) 
    }
    addPloygon = function (id, arr, height,i,type,data,event) {
        var gradient = [];
        function gradientColor(startColor, endColor, step) {
            var startRGB = this.colorRgb(startColor);//转换为rgb数组模式
            var startR = startRGB[0];
            var startG = startRGB[1];
            var startB = startRGB[2];
            var endRGB = this.colorRgb(endColor);
            var endR = endRGB[0];
            var endG = endRGB[1];
            var endB = endRGB[2];
        
            var sR = (endR - startR) / step;//总差值
            var sG = (endG - startG) / step;
            var sB = (endB - startB) / step;
        
            var colorArr = [];
            for (var i = 0; i < step; i++) {
                //计算每一步的hex值 
                var hex = this.colorHex('rgba('+ parseInt((sR * i + startR))+ ',' + parseInt((sG * i + startG))+ ',' + parseInt((sB * i + startB)) + ',.7)');
                colorArr.push(hex);
            }
            gradient = colorArr;
            //return colorArr;
        }
        // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
        gradientColor.prototype.colorRgb = function(sColor) {
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            var sColor = sColor.toLowerCase();
            if (sColor && reg.test(sColor)) {
                if (sColor.length === 4) {
                    var sColorNew = "#";
                    for (var i = 1; i < 4; i += 1) {
                        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                    }
                    sColor = sColorNew;
                }
                //处理六位的颜色值
                var sColorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
                }
                return sColorChange;
            } else {
                return sColor;
            }
        };
        // 将rgb表示方式转换为hex表示方式
        gradientColor.prototype.colorHex = function(rgb) {
            var _this = rgb;
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            if (/^(rgb|RGB)/.test(_this)) {
                var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
                var strHex = "#";
                for (var i = 0; i < aColor.length; i++) {
                    var hex = Number(aColor[i]).toString(16);
                    hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
                    if (hex === "0") {
                        hex += hex;
                    }
                    strHex += hex;
                }
                if (strHex.length !== 7) {
                    strHex = _this;
                }
                return strHex;
            } else if (reg.test(_this)) {
                var aNum = _this.replace(/#/, "").split("");
                if (aNum.length === 6) {
                    return _this;
                } else if (aNum.length === 3) {
                    var numHex = "#";
                    for (var i = 0; i < aNum.length; i += 1) {
                        numHex += (aNum[i] + aNum[i]);
                    }
                    return numHex;
                }
            } else {
                return _this;
            }
        }
        function rn(min,max){
            return Math.floor(Math.random()*(max-min)+min);
        }
        function rc(){
            // var r = rn(1,152);
            // var g = rn(102,204);
            // var b = rn(0,101);
            var r = rn(76,220);
            var g = rn(73,221);
            var b = rn(38,155);
            return "rgba("+r+','+g+','+b+',.8)';
        }
        new gradientColor('#00FFFF','#E1FFFF', 19); 
        let simplePointEntity =this.viewer.entities.add({
            id: id,
            datas:data,
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
                material: Cesium.Color.fromCssColorString(gradient[i]).withAlpha(.9),
                extrudedHeight : height
                //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            },
            polyline: {
                positions: Cesium.Cartesian3.fromDegreesArray(arr),
                clampToGround: true,
                width: 2,
                material: new Cesium.PolylineOutlineMaterialProperty({
                    //color: Cesium.Color.fromCssColorString("#204789"),
                    color:  Cesium.Color.DARKTURQUOISE,
                    outlineWidth: 1,
                    outlineColor: Cesium.Color.BLACK,
                }),
            },
        });
        if (type && event) {
            simplePointEntity[type] = event
        }
    }
    addOnlyLabel = function (id, position, height, text , type, event,data) {
        let simplePointEntity = this.viewer.entities.add({
            id: id, //
            datatype:data,
            position: Cesium.Cartesian3.fromDegrees(position[0], position[1], height*1),
            label: {
                text: text,
                show: true,
                font: '10pt Source Han Sans CN', //字体样式
                fillColor: Cesium.Color.BLACK, //字体颜色
                backgroundColor: Cesium.Color.GREY, //背景颜色
                showBackground: false, //是否显示背景颜色
                outlineColor: Cesium.Color.DARKGOLDENROD,
                style: Cesium.LabelStyle.BLACK, //label样式
                outlineWidth: 1,
               // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
                pixelOffset: new Cesium.Cartesian2(0, 0) //偏移
            },
            cursor: true
        })
        simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
        if (type && event) {
            simplePointEntity[type] = event
        }
    }
    addOnlyLabelWithColor = function (id, position, height, text , type, event) {
        let simplePointEntity = this.viewer.entities.add({
            id: id, //
            position: Cesium.Cartesian3.fromDegrees(position[0], position[1], height*1),
            label: {
                text: text,
                show: true,
                font: '15pt Source Han Sans CN', //字体样式
                fillColor: Cesium.Color.AQUA, //字体颜色
                backgroundColor: Cesium.Color.GREY, //背景颜色
                showBackground: false, //是否显示背景颜色
                outlineColor: Cesium.Color.DARKGOLDENROD,
                style: Cesium.LabelStyle.BLACK, //label样式
                outlineWidth: 1,
               
               // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //垂直位置
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
                pixelOffset: new Cesium.Cartesian2(0, -50) //偏移
            },
            cursor: true
        })
        simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
        if (type && event) {
            simplePointEntity[type] = event
        }
    }
    // cesium 聚合
    polymerization(data,image){
        let that = this
        let polymericDataSource = new Cesium.CustomDataSource('StaticDataSource');
        that.polymericDataSource =  polymericDataSource.entities;
        for(let i = 0; i<data.length; i++){
            if(data[i].lon){
                that.polymericDataSource.add({
                    position: Cesium.Cartesian3.fromDegrees(parseFloat(data[i].lon), parseFloat(data[i].lat), 10),
                    billboard: {
                        name:data[i].name,
                        scale:0.8,
                        image:image,
                        width: 40,
                        height: 40,
                    },
                    label:{
                        text:data[i].name,
                        show:true,
                        font: '10pt Source Han Sans CN',
                        pixelOffset: new Cesium.Cartesian2(0, -30)
                    }
                })
                
            }
            
            
        }
        var dataSourcePromise = viewer.dataSources.add(polymericDataSource);
        dataSourcePromise.then(function(dataSource) {
            var pixelRange = 15;
            var minimumClusterSize = 3;
            var enabled = true;
            dataSource.clustering.enabled = enabled;
            dataSource.clustering.pixelRange = pixelRange;
            dataSource.clustering.minimumClusterSize = minimumClusterSize;

            var removeListener;

            var pinBuilder = new Cesium.PinBuilder();
            // var pin50 = pinBuilder.fromText('50+', Cesium.Color.RED, 48).toDataURL();
            // var pin40 = pinBuilder.fromText('40+', Cesium.Color.ORANGE, 48).toDataURL();
            // var pin30 = pinBuilder.fromText('30+', Cesium.Color.YELLOW, 48).toDataURL();
            // var pin20 = pinBuilder.fromText('20+', Cesium.Color.GREEN, 48).toDataURL();
            // var pin10 = pinBuilder.fromText('10+', Cesium.Color.BLUE, 48).toDataURL();
            var singleDigitPins = new Array(8);
            for (var i = 0; i < singleDigitPins.length; ++i) {
                singleDigitPins[i] = pinBuilder.fromText('' + (i + 2), Cesium.Color.VIOLET, 48).toDataURL();
            }
            function customStyle() {
                if (Cesium.defined(removeListener)) {
                    removeListener();
                    removeListener = undefined;
                } else {
                    removeListener = dataSource.clustering.clusterEvent.addEventListener(function(clusteredEntities, cluster) {
                        cluster.label.show = false;
                        cluster.billboard.show = true;
                        cluster.billboard.id = cluster.label.id;
                        cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;

                        if (clusteredEntities.length >= 1000) {
                            cluster.billboard.image = pinBuilder.fromText('' + clusteredEntities.length, Cesium.Color.RED, 48).toDataURL();//pin50;
                        } else if (clusteredEntities.length >= 500) {
                            cluster.billboard.image = pinBuilder.fromText('' + clusteredEntities.length, Cesium.Color.ORANGE, 48).toDataURL();//pin40;
                        } else if (clusteredEntities.length >= 300) {
                            cluster.billboard.image = pinBuilder.fromText('' + clusteredEntities.length, Cesium.Color.YELLOW, 48).toDataURL();
                        } else if (clusteredEntities.length >= 150) {
                            cluster.billboard.image = pinBuilder.fromText('' + clusteredEntities.length, Cesium.Color.GREEN, 48).toDataURL();
                        } else if (clusteredEntities.length >= 10) {
                            cluster.billboard.image = pinBuilder.fromText('' + clusteredEntities.length, Cesium.Color.BLUE, 48).toDataURL();
                        } else {
                            cluster.billboard.image = singleDigitPins[clusteredEntities.length - 2];
                        }
                    });
                }
                var pixelRange = dataSource.clustering.pixelRange;
                dataSource.clustering.pixelRange = 0;
                dataSource.clustering.pixelRange = pixelRange;
            }
            customStyle();
            function subscribeParameter(name) {
                Cesium.knockout.getObservable(viewModel, name).subscribe(
                    function(newValue) {
                        dataSource.clustering[name] = newValue;
                    }
                );
            }
            subscribeParameter('pixelRange');
            subscribeParameter('minimumClusterSize');
        })
    }
    polymerizationRemove (){
        if(this.polymericDataSource){
            this.polymericDataSource.removeAll()
            this.polymericDataSource = null;
        }
    }
    getXy(){
        var that = this;
        let handler3D = new Cesium.ScreenSpaceEventHandler( viewer.scene.canvas);
            handler3D.setInputAction(function(movement) {
                viewer.scene.globe.depthTestAgainstTerrain = true;
                var earthPosition = viewer.scene.pickPosition(movement.position);
                var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(earthPosition);  // longitude, latitude, height
                var point=[ cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];
              
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    remove3dTiles(){
        if(this.Tile !== null){
            viewer.scene.primitives.remove(this.Tile)
            this.Tile = null;
        }
        if(this.vecTile !== null){
            viewer.scene.primitives.remove(this.vecTile)
            this.vecTile = null;
        }
        // viewer.scene.primitives.removeAll()
    }
    add3dTiles(url){
        let tilesetModel = new Cesium.Cesium3DTileset({
            url
        });
        tilesetModel.readyPromise.then(function (argument) {
            viewer.scene.primitives.add(tilesetModel);
            viewer.zoomTo(tilesetModel);
        }).otherwise(function (error) {
            
        });
        return tilesetModel;
    }
    juliceliang() {
        var viewer = this.viewer;
        // 取消双击事件-追踪该位置
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
            Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );
    
        var handler = new Cesium.ScreenSpaceEventHandler(
            viewer.scene._imageryLayerCollection
        );
        var positions = [];
        var poly = null;
        // var tooltip = document.getElementById("toolTip");
        var distance = 0;
        var cartesian = null;
        var floatingPoint;
        var floatingPointArr = [];
        // tooltip.style.display = "block";
    
        handler.setInputAction(function (movement) {
            // tooltip.style.left = movement.endPosition.x + 3 + "px";
            // tooltip.style.top = movement.endPosition.y - 25 + "px";
            // tooltip.innerHTML = '<p>单击开始，右击结束</p>';
            // cartesian = viewer.scene.pickPosition(movement.endPosition);
            let ray = viewer.camera.getPickRay(movement.endPosition);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
            if (positions.length >= 2) {
                if (!Cesium.defined(poly)) {
                    poly = new PolyLinePrimitive(positions);
                } else {
                    positions.pop();
                    // cartesian.y += (1 + Math.random());
                    positions.push(cartesian);
                }
                distance = getSpaceDistance(positions);
                // console.log("distance: " + distance);
                // tooltip.innerHTML='<p>'+distance+'米</p>';
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    
        handler.setInputAction(function (movement) {
            // tooltip.style.display = "none";
            // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
            // cartesian = viewer.scene.pickPosition(movement.position);
            let ray = viewer.camera.getPickRay(movement.position);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            if (positions.length == 0) {
                positions.push(cartesian.clone());
            }
            positions.push(cartesian);
            //在三维场景中添加Label
            //   var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            var textDisance = distance + "米";
            // console.log(textDisance + ",lng:" + cartographic.longitude/Math.PI*180.0);
            floatingPoint = viewer.entities.add({
                name: "空间直线距离",
                // position: Cesium.Cartesian3.fromDegrees(cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180,cartographic.height),
                position: positions[positions.length - 1],
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2
                },
                label: {
                    text: textDisance,
                    font: "18px sans-serif",
                    fillColor: Cesium.Color.GOLD,
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    outlineWidth: 2,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    pixelOffset: new Cesium.Cartesian2(20, -20)
                }
            });
            floatingPointArr.push(floatingPoint);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
        handler.setInputAction(function (movement) {
            handler.destroy(); //关闭事件句柄
            // viewer.entities.remove(floatingPoint);
            //添加删除按钮
            var deleteBtn = viewer.entities.add({
                id: "deleteBtn",
                position: positions[positions.length - 1],
                //广告牌
                billboard: {
                    image:
                        "",
                    width: 20,
                    height: 20,
                    verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                    pixelOffset: Cesium.Cartesian2(-60, 60)
                }
            });
            var handler1 = new Cesium.ScreenSpaceEventHandler(
                viewer.scene._imageryLayerCollection
            );
            handler1.setInputAction(function (click) {
                var pick = viewer.scene.pick(click.position);
                //选中某模型   pick选中的对象
                if (Cesium.defined(pick) && pick.id.id === "deleteBtn") {
                    for (var i = 0; i < floatingPointArr.length; i++) {
                        viewer.entities.remove(floatingPointArr[i]);
                    }
                    viewer.entities.remove(deleteBtn);
                    handler1.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                    handler1.destroy();
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
            positions.pop(); //最后一个点无效
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    
        var PolyLinePrimitive = (function () {
            function _(positions) {
                this.options = {
                    name: "直线",
                    polyline: {
                        show: true,
                        positions: [],
                        material: Cesium.Color.CHARTREUSE,
                        width: 10,
                        clampToGround: true
                    }
                };
                this.positions = positions;
                this._init();
            }
    
            _.prototype._init = function () {
                var _self = this;
                var _update = function () {
                    return _self.positions;
                };
                //实时更新polyline.positions
                this.options.polyline.positions = new Cesium.CallbackProperty(
                    _update,
                    false
                );
                var lineEneity = viewer.entities.add(this.options);
                floatingPointArr.push(lineEneity);
            };
    
            return _;
        })();
        //空间两点距离计算函数
        function getSpaceDistance(positions) {
            var distance = 0;
            for (var i = 0; i < positions.length - 1; i++) {
                var point1cartographic = Cesium.Cartographic.fromCartesian(
                    positions[i]
                );
                var point2cartographic = Cesium.Cartographic.fromCartesian(
                    positions[i + 1]
                );
                /**根据经纬度计算出距离**/
                var geodesic = new Cesium.EllipsoidGeodesic();
                geodesic.setEndPoints(point1cartographic, point2cartographic);
                var s = geodesic.surfaceDistance;
                //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
                //返回两点之间的距离
                s = Math.sqrt(
                    Math.pow(s, 2) +
                    Math.pow(point2cartographic.height - point1cartographic.height, 2)
                );
                distance = distance + s;
            }
            return distance.toFixed(2);
        }
    }
    //面积计算
    mianjiceliang() {
        var viewer = this.viewer;
        // 取消双击事件-追踪该位置
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
            Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );
        // 鼠标事件
        var handler = new Cesium.ScreenSpaceEventHandler(
            viewer.scene._imageryLayerCollection
        );
        var positions = [];
        var tempPoints = [];
        var polygon = null;
        // var tooltip = document.getElementById("toolTip");
        var cartesian = null;
        var floatingPoint; //浮动点
        // tooltip.style.display = "block";
        var floatingPointArr = [];
        handler.setInputAction(function (movement) {
            // tooltip.style.left = movement.endPosition.x + 3 + "px";
            // tooltip.style.top = movement.endPosition.y - 25 + "px";
            // tooltip.innerHTML ='<p>单击开始，右击结束</p>';
            // cartesian = viewer.scene.pickPosition(movement.endPosition);
            let ray = viewer.camera.getPickRay(movement.endPosition);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
            if (positions.length >= 2) {
                if (!Cesium.defined(polygon)) {
                    polygon = new PolygonPrimitive(positions);
                } else {
                    positions.pop();
                    // cartesian.y += (1 + Math.random());
                    positions.push(cartesian);
                }
                // tooltip.innerHTML='<p>'+distance+'米</p>';
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    
        handler.setInputAction(function (movement) {
            // tooltip.style.display = "none";
            // cartesian = viewer.scene.pickPosition(movement.position);
            let ray = viewer.camera.getPickRay(movement.position);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
            if (positions.length == 0) {
                positions.push(cartesian.clone());
            }
            //positions.pop();
            positions.push(cartesian);
            //在三维场景中添加点
            var cartographic = Cesium.Cartographic.fromCartesian(
                positions[positions.length - 1]
            );
            var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
            var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
            var heightString = cartographic.height;
            tempPoints.push({
                lon: longitudeString,
                lat: latitudeString,
                hei: heightString
            });
            floatingPoint = viewer.entities.add({
                name: "多边形面积",
                position: positions[positions.length - 1],
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2
                }
            });
            floatingPointArr.push(floatingPoint);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
        handler.setInputAction(function (movement) {
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            handler.destroy();
            positions.pop();
            viewer.entities.remove(floatingPoint);
            //tempPoints.pop();
            // viewer.entities.remove(floatingPoint);
            // tooltip.style.display = "none";
            //在三维场景中添加点
            // var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
            // var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
            // var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
            // var heightString = cartographic.height;
            // tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});
            var deleteBtn = viewer.entities.add({
                id: "deleteBtn",
                position: positions[positions.length - 1],
                //广告牌
                billboard: {
                    image:
                        "",
                    width: 20,
                    height: 20
                }
            });
            var handler1 = new Cesium.ScreenSpaceEventHandler(
                viewer.scene._imageryLayerCollection
            );
            handler1.setInputAction(function (click) {
                var pick = viewer.scene.pick(click.position);
                //选中某模型   pick选中的对象
                if (Cesium.defined(pick) && pick.id.id === "deleteBtn") {
                    for (var i = 0; i < floatingPointArr.length; i++) {
                        viewer.entities.remove(floatingPointArr[i]);
                    }
                    viewer.entities.remove(deleteBtn);
                    handler1.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                    handler1.destroy();
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            var textArea = getArea(tempPoints) + "平方公里";
            var areaEntity = viewer.entities.add({
                name: "多边形面积",
                position: positions[positions.length - 1],
                // point : {
                //  pixelSize : 5,
                //  color : Cesium.Color.RED,
                //  outlineColor : Cesium.Color.WHITE,
                //  outlineWidth : 2,
                //  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
                // },
                label: {
                    text: textArea,
                    font: "18px sans-serif",
                    fillColor: Cesium.Color.GOLD,
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    outlineWidth: 2,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    pixelOffset: new Cesium.Cartesian2(20, -40),
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                }
            });
            floatingPointArr.push(areaEntity);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    
        var radiansPerDegree = Math.PI / 180.0; //角度转化为弧度(rad)
        var degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度
    
        //计算多边形面积
        function getArea(points) {
            var res = 0;
            //拆分三角曲面
    
            for (var i = 0; i < points.length - 2; i++) {
                var j = (i + 1) % points.length;
                var k = (i + 2) % points.length;
                var totalAngle = Angle(points[i], points[j], points[k]);
    
                var dis_temp1 = distance(positions[i], positions[j]);
                var dis_temp2 = distance(positions[j], positions[k]);
                res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
                
            }
    
            return (res / 1000000.0).toFixed(4);
        }
    
        /*角度*/
        function Angle(p1, p2, p3) {
            var bearing21 = Bearing(p2, p1);
            var bearing23 = Bearing(p2, p3);
            var angle = bearing21 - bearing23;
            if (angle < 0) {
                angle += 360;
            }
            return angle;
        }
        /*方向*/
        function Bearing(from, to) {
            var lat1 = from.lat * radiansPerDegree;
            var lon1 = from.lon * radiansPerDegree;
            var lat2 = to.lat * radiansPerDegree;
            var lon2 = to.lon * radiansPerDegree;
            var angle = -Math.atan2(
                Math.sin(lon1 - lon2) * Math.cos(lat2),
                Math.cos(lat1) * Math.sin(lat2) -
                Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
            );
            if (angle < 0) {
                angle += Math.PI * 2.0;
            }
            angle = angle * degreesPerRadian; //角度
            return angle;
        }
    
        var PolygonPrimitive = (function () {
            function _(positions) {
                this.options = {
                    name: "多边形",
                    polygon: {
                        hierarchy: [],
                        // perPositionHeight : true,
                        material: Cesium.Color.GREEN.withAlpha(0.5)
                        // heightReference:20000
                    }
                };
    
                this.hierarchy = { positions };
                this._init();
            }
    
            _.prototype._init = function () {
                var _self = this;
                var _update = function () {
                    return _self.hierarchy;
                };
                //实时更新polygon.hierarchy
                this.options.polygon.hierarchy = new Cesium.CallbackProperty(
                    _update,
                    false
                );
                var polygonEntity = viewer.entities.add(this.options);
                floatingPointArr.push(polygonEntity);
            };
    
            return _;
        })();
    
        function distance(point1, point2) {
            var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
            var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
            /**根据经纬度计算出距离**/
            var geodesic = new Cesium.EllipsoidGeodesic();
            geodesic.setEndPoints(point1cartographic, point2cartographic);
            var s = geodesic.surfaceDistance;
            //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
            //返回两点之间的距离
            s = Math.sqrt(
                Math.pow(s, 2) +
                Math.pow(point2cartographic.height - point1cartographic.height, 2)
            );
            return s;
        }
    }
    
}